package top.ivansong92.example.leetcode.learning.data.struct.linklist.extension;

import top.ivansong92.example.leetcode.learning.data.struct.array.extension.queue.NewQueue;

public class NewLinkedQueue<E> implements NewQueue<E> {
    private Node<E> head, tail;
    private int size;

    public NewLinkedQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public void enqueue(E e) {
        if (tail == null) {
            head = tail = new Node<>(e);
        } else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size ++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        Node node = head;
        head = head.next;
        if (head == null) {
            tail = null;
        }
        node.next = null;
        size --;
        return (E) node.e;
    }

    @Override
    public E getHeader() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        return head.e;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    private static class Node<E> {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }


        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }
    }
}
